/**
 * Created by hao.cheng on 2017/4/16.
 */
import React from "react";
import {Button, Form, Input, Modal, Select, Table} from "antd";
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import {fetchData, receiveData} from "@/action";
import request, {get} from "@/axios/tools";

const FormItem = Form.Item;
const Option = Select.Option;

class ManagerUser extends React.Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            data: [], createUser: false, loading: false, roles: [],
            editLoading: false, editUser: false, editData: {}
        };
    }

    componentDidMount() {
        this._listUser();
        this._listRole();
    }


    _listUser = () => {
        get('/user/listUser').then(data => {
            data = data.map(v => {
                return {...v, key: v.id};
            });
            this.setState({data});
        });
    };

    _deleteUser = id => {
        request({url: "/user/item/" + id, method: 'delete'}).then(data => {
            const newData = this.state.data.filter(v => id !== v.id);
            this.setState({data: newData});
        });
    };

    _addUser = values => {
        const form = this.form;
        const {auth: auth = {data: {}}} = this.props;
        const {data} = auth;
        if (data && data.restaurant) {
            this.setState({loading: true});
            let roles = values.roles.map(v => {
                return {id: v};
            });
            request({
                url: '/user/item',
                method: 'post',
                body: {...values, restaurantID: data.restaurant, roles}
            }).then(data => {
                form.resetFields();
                this.setState({createUser: false, loading: false});
                this._listUser();
            }).catch(e => {
                this.setState({loading: false});
            });
        }
    };

    _listRole = () => {
        get('/user/roles').then(data => {
            this.setState({roles: data});
        });
    };

    _editUser = () => {
        const form = this.editForm;
        const user = this.state.editData;
        this.setState({editLoading: true});
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            const roles = values.roles.map(v => {
                return {id: v};
            });
            const postData = {id: user.id, realName: values.realName, roles};
            request({url: '/user/item', method: 'put', body: postData}).then(data => {
                const newData = this.state.data.map(v => {
                    return v.id === data.id ? {...data, key: data.id} : v;
                });
                form.resetFields();
                this.setState({data: newData, editLoading: false, editUser: false, editData: {}});
            }).catch(e => {
                this.setState({editLoading: false});
                console.error('_editUser  erro   ', e);
            });
        });
    };

    handleCreate = () => {
        const form = this.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            this._addUser(values);
        });
    };
    saveFormRef = (form) => {
        this.form = form;
    };


    render() {
        const {data} = this.state;
        const columns = [{title: 'ID', dataIndex: 'id'}, {title: '用户名', dataIndex: 'name'}, {
            title: '真实名',
            dataIndex: 'realName'
        }, {
            title: '操作',
            dataIndex: 'action',
            render: (text, data) => {
                return <div>
                    <Button onClick={e => {
                        this.setState({editData: data, editUser: true});
                    }}>编辑</Button>
                    <Button onClick={e => {
                        this._deleteUser(data.id)
                    }}>删除</Button>
                </div>
            }
        },];
        return (
            <div className="content-container">
                <Button onClick={e => {
                    this.setState({createUser: true});
                }}>添加</Button>
                <div className="space-bar"/>
                <Table dataSource={data} columns={columns}/>
                <CreateUser ref={this.saveFormRef}
                            data={{}}
                            roles={this.state.roles}
                            visible={this.state.createUser}
                            loading={this.state.loading}
                            title={'创建新用户'}
                            onCancel={e => {
                                this.setState({createUser: false});
                            }}
                            onCreate={this.handleCreate}/>
                <CreateUser ref={v => {
                    this.editForm = v;
                }}
                            edit={true}
                            data={this.state.editData}
                            roles={this.state.roles}
                            visible={this.state.editUser}
                            loading={this.state.editLoading}
                            title={'创建新用户'}
                            onCancel={e => {
                                this.setState({editUser: false});
                            }}
                            onCreate={this._editUser}/>
            </div>
        );
    }
}

const CreateUser = Form.create()(
    (props) => {
        const {data, visible, onCancel, onCreate, form, loading, roles, title, edit} = props;
        const {getFieldDecorator} = form;
        const list = data.roles;
        let selectList = [];
        if (Array.isArray(list)) {
            selectList = list.map(v => String(v.id));
        }
        return (
            <Modal
                visible={visible}
                title={title}
                onCancel={onCancel}
                footer={null}
            >
                <Form layout="vertical">
                    <FormItem label="用户名">
                        {getFieldDecorator('name', {
                            rules: [{required: true, message: '请输入用户名'}],
                            initialValue: data.name
                        })(
                            <Input disabled={edit}/>
                        )}
                    </FormItem>
                    <FormItem label="密码">
                        {getFieldDecorator('password', {
                            rules: [{required: !edit, message: '请输入密码'}],
                            initialValue: data.password
                        })(
                            <Input disabled={edit}/>
                        )}
                    </FormItem>
                    <FormItem label="真实名">
                        {getFieldDecorator('realName', {
                            rules: [{required: false, message: '请输入真实姓名'}],
                            initialValue: data.realName
                        })(
                            <Input />
                        )}
                    </FormItem>
                    <FormItem
                        label="角色"
                    >
                        {getFieldDecorator('roles', {
                            rules: [{required: false, message: '请选择角色'}],
                            initialValue: selectList
                        })(
                            <Select
                                mode="multiple"
                            >{roles.map(v => {
                                return <Option key={v.id} value={String(v.id)}>{v.nickName || ''}</Option>
                            })}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem>
                        <Button
                            type="primary"
                            htmlType="submit"
                            onClick={onCreate}
                            loading={loading}
                        >
                            提交
                        </Button>
                    </FormItem>
                </Form>
            </Modal>
        );
    }
);

const mapStateToPorps = state => {
    const {auth} = state.httpData;
    return {auth};
};
const mapDispatchToProps = dispatch => ({
    fetchData: bindActionCreators(fetchData, dispatch),
    receiveData: bindActionCreators(receiveData, dispatch)
});


export default connect(mapStateToPorps, mapDispatchToProps)(Form.create()(ManagerUser));